/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.center.web.action.config;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.bean.Page;
import com.sinodata.bsm.center.bean.RelationHelper;
import com.sinodata.bsm.center.bean.ResBean;
import com.sinodata.bsm.center.cache.ResViewCache;
import com.sinodata.bsm.center.cache.ResViewRelCache;
import com.sinodata.bsm.center.service.resource.ResViewService;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.exception.AppException;
import com.sinodata.bsm.common.vo.ResView;
import com.sinodata.bsm.common.vo.ResViewRel;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author dongyushi
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-5-21 上午11:19:06          dongyushi        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class ResourceViewConfigAction extends BaseAction<ResView> {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = -2423730569613866497L;

    private Long[] ids;

    private Long id;

    private ResView entity;

    @Autowired
    private ResViewService resViewService;
    @Autowired
    private ResViewCache resViewCache;
    @Autowired
    private ResViewRelCache resViewRelCache;

    @Action("resourceviewconfig")
    public String common() {
        return "common";
    }

    public String add() {
        return "add";
    }

    /**
     * 查询列表
     * @throws IOException
     */
    @Override
    public String list() throws IOException {
        Page<ResView> page = new Page<ResView>();
        page.setPageNo(Integer.valueOf(request.getParameter("iDisplayStart")) / Integer.valueOf(request.getParameter("iDisplayLength")) + 1);
        page.setPageSize(Integer.valueOf(request.getParameter("iDisplayLength")));
        Page<ResView> aaData = resViewService.findByPage(page);

        JSONObject json = new JSONObject();
        json.element("iTotalRecords", page.getTotal());
        json.element("iTotalDisplayRecords", page.getTotal());
        JSONArray array = new JSONArray();
        for (ResView resView : aaData.getRows()) {

            JSONObject obj = new JSONObject();
            obj.element("checkbox", "<div><input type='checkbox' name='dt_check' id='dt_check' value='" + resView.getId() + "'></div>");
            obj.element("op", "<div style='width: 60px'>&nbsp;&nbsp;<a href='javascript:edit(" + resView.getId() + ");'><img src='../style/default/bsm/images/edit.gif' title='修改'></a>&nbsp;&nbsp;<a href='javascript:deleteOne(" + resView.getId() + ");'><img src='../style/default/bsm/images/delete.gif'  title='删除'></a>");
            obj.element("id", resView.getId());
            obj.element("name", resView.getName());
            obj.element("expandLevel", resView.getExpandLevel());
            // obj.element("resId", resView.getResId());
            array.add(obj);
        }
        json.element("aaData", array);
        renderText(json.toString());
        return null;

    }

    /**
     * 保存
     * @throws IOException
     */
    @Override
    public String save() throws IOException {
        String resRelId = request.getParameter("resRelId");
        if (entity.getId() != null) {
            if (resViewCache.get(entity.getId()) != null) {
                resViewService.update(entity);
                List<ResViewRel> relList = resViewService.getResViewRelByViewId(entity.getId());
                if (relList == null) {
                    relList = new ArrayList<ResViewRel>();
                }

                if (resRelId != null && !resRelId.equals("")) {
                    String[] resIds = resRelId.split("[,]");

                    // deleted it
                    for (int j = relList.size() - 1; j >= 0; j--) {
                        long oldVal = relList.get(j).getResId();
                        boolean found = false;
                        for (int i = 0; i < resIds.length; i++) {
                            if (Long.parseLong(resIds[i]) == oldVal) {
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            //deleted it
                            resViewService.deleteResViewRel(relList.get(j));
                            resViewRelCache.remove(relList.get(j).getId());
                        }
                    }
                    relList = resViewService.getResViewRelByViewId(entity.getId());

                    for (int i = 0; i < resIds.length; i++) {
                        long resId = Long.parseLong(resIds[i]);
                        boolean found = false;
                        for (int j = 0; relList != null && j < relList.size(); j++) {
                            if (relList.get(j).getResId() == resId) {
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            // add it
                            ResViewRel rel = new ResViewRel();
                            rel.setResViewId(entity.getId());
                            rel.setResId(resId);
                            resViewService.saveResViewRel(rel);
                        }
                    }

                }
                resViewCache.put(entity.getId(), entity);
            } else {
                renderText("false");
                return null;
            }
        } else {
            resViewService.add(entity);
            resViewCache.put(entity.getId(), entity);
        }
        renderText("true");
        return null;
    }

    public String checkDeleted() {
        JSONObject ob = new JSONObject();
        if (resViewCache.get(id) == null) {
            ob.element("flag", false);
        } else {
            ob.element("flag", true);
        }
        Struts2Utils.renderJson(ob.toString());
        return null;
    }

    /**
     * 删除
     * @throws AppException 
     */
    @Override
    public String delete() throws AppException {
        //缓存判断是否被删除
        for (Long id : ids) {
            if (id == 1) {
                return null;
            }
            if (resViewCache.get(id) == null) {
                return null;
            }
        }

        //判断要删除的视图下有没有资源
        for (Long viewId : ids) {
            List<ResViewRel> list = resViewRelCache.getResViewRelByViewId(viewId);
            if (list != null && list.size() > 0) {
                renderText("false");
                return null;
            }
        }
        ResView resView = resViewService.delete(ids);
        //缓存 循环操作
        for (Long id : ids) {
            resViewCache.remove(id);
        }
        if (resView != null) {
            resViewCache.put(resView.getId(), resView);
        }
        request.getSession().removeAttribute("lastView");

        renderText("true");

        return null;
    }

    public Long[] getIds() {
        return ids;
    }

    public void setIds(Long[] ids) {
        this.ids = ids;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#input()
     */
    @Override
    public String input() throws Exception {
        ResView resView = resViewService.get(Long.valueOf(request.getParameter("id")));
        List<ResViewRel> relList = resViewService.getResViewRelByViewId(resView.getId());
        if (relList == null) {
            relList = new ArrayList<ResViewRel>();
        }
        List<Long> notDeleteList = new ArrayList<Long>();
        for (ResViewRel rel : relList) {
            Long resId = rel.getResId();
            List<ResBean> pList = RelationHelper.parents(resId);
            if (pList == null || pList.size() == 0) {
                notDeleteList.add(resId);
            }
        }
        request.setAttribute("notDeleteList", notDeleteList);
        request.setAttribute("relList", relList);
        Struts2Utils.getRequest().setAttribute("resView", resView);
        return "update";
    }

    /* (non-Javadoc)
     * @see com.opensymphony.xwork2.ModelDriven#getModel()
     */
    @Override
    public ResView getModel() {
        return entity;
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#prepareModel()
     */
    @Override
    protected void prepareModel() throws Exception {
        if (id != null) {
            entity = resViewService.get(id);
            if (entity == null) {
                entity = new ResView();
            }
        } else {
            entity = new ResView();
        }
    }

}
